<template>
	<view class="search-container">
		<!-- 搜索框区域 -->
		<view class="search-bar">
			<view class="search-input-wrapper">
				<input class="search-input" placeholder="搜索直播/主播" v-model="searchKeyword" @input="handleInputChange"
					@confirm="handleSearch" confirm-type="search" />
				<view v-if="searchKeyword" class="clear-btn" @click="clearSearchInput">
					<uni-icons type="clear" size="18" color="#999"></uni-icons>
				</view>
			</view>
			<view class="search-button" @click="handleSearch">搜索</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading-state" v-if="isSearching">
			<uni-load-more status="loading"></uni-load-more>
		</view>

		<!-- 搜索建议 -->
		<view class="suggestion-list" v-if="showSuggestions && searchKeyword && !isSearching">
			<view class="suggestion-item" v-for="(item, index) in suggestions" :key="index"
				@click="selectSuggestion(item)">
				<rich-text :nodes="highlightKeyword(item, searchKeyword)"></rich-text>
			</view>
		</view>

		<!-- 初始状态：搜索历史 -->
		<view class="initial-state" v-if="!searchKeyword && !showResults && !showEmpty && !networkError">
			<view class="history-section" v-if="searchHistory.length > 0">
				<view class="section-header">
					<text>搜索历史</text>
					<text class="clear-all" @click="clearAllHistory">清空</text>
				</view>
				<view class="history-list">
					<view class="history-item" v-for="(item, index) in searchHistory" :key="index"
						@click="selectHistory(item)">
						<text>{{ item }}</text>
						<view class="delete-btn" @click.stop="handleDeleteHistory(index, $event)">
							<uni-icons type="close" size="14" color="#999"></uni-icons>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 搜索结果状态 -->
		<view class="result-state" v-if="showResults && !isSearching && !networkError">
			<view class="result-header">
				<text>搜索"{{ lastSearchKeyword }}"的结果</text>
				<text class="reset-search" @click="resetSearch">清除搜索</text>
			</view>
			<view class="result-list">
				<view class="result-item" v-for="(item, index) in searchResults" :key="index">
					<rich-text :nodes="highlightKeyword(item.title, lastSearchKeyword)"></rich-text>
					<text class="subtitle">{{ item.type === 'live' ? '直播' : '主播' }}</text>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="showEmpty && !isSearching && !networkError">
			<image src="/static/empty.png" class="empty-icon"></image>
			<text class="empty-text">未找到"{{ lastSearchKeyword }}"相关结果</text>
			<text class="empty-tip">换个关键词试试</text>
		</view>

		<!-- 网络错误状态 -->
		<view class="network-error" v-if="networkError && !isSearching">
			<image src="/static/network-error.png" class="error-icon"></image>
			<text class="error-text">搜索失败，请检查网络</text>
			<view class="retry-btn" @click="retrySearch">重新搜索</view>
		</view>
	</view>
</template>

<script>
	// 模拟用户数据
	const mockUsers = [{
			id: 1,
			title: '健康知识讲座',
			type: 'live',
			tags: ['健康', '医疗']
		},
		{
			id: 2,
			title: '健身达人秀',
			type: 'live',
			tags: ['健身', '运动']
		},
		{
			id: 3,
			title: '美食烹饪课',
			type: 'live',
			tags: ['美食', '烹饪']
		},
		{
			id: 4,
			title: '小蘑菇',
			type: 'anchor',
			tags: ['健康', '讲师']
		},
		{
			id: 5,
			title: '运动健将',
			type: 'anchor',
			tags: ['健身', '教练']
		}
	]

	export default {
		data() {
			return {
				searchKeyword: '',
				lastSearchKeyword: '',
				searchHistory: [],
				suggestions: [],
				searchResults: [],
				showSuggestions: false,
				showResults: false,
				showEmpty: false,
				networkError: false,
				isSearching: false,
				searchTimer: null
			}
		},
		onLoad() {
			this.loadSearchHistory()
		},
		methods: {
			// 加载搜索历史
			loadSearchHistory() {
				this.searchHistory = uni.getStorageSync('searchHistory') || []
			},

			// 检查网络连接
			async checkNetworkConnection() {
				try {
					const networkType = await new Promise((resolve, reject) => {
						uni.getNetworkType({
							success: res => resolve(res.networkType),
							fail: err => reject(err)
						})
					})
					return networkType !== 'none'
				} catch (error) {
					console.error('网络检测失败:', error)
					return false
				}
			},

			// 输入处理
			handleInputChange() {
				clearTimeout(this.searchTimer)

				if (!this.searchKeyword) {
					this.resetToInitialState()
					return
				}

				this.searchTimer = setTimeout(() => {
					this.getSearchSuggestions()
				}, 300)
			},

			// 获取搜索建议
			getSearchSuggestions() {
				this.suggestions = mockUsers
					.filter(item =>
						item.title.includes(this.searchKeyword) ||
						item.tags.some(tag => tag.includes(this.searchKeyword))
					)
					.map(item => item.title)
					.slice(0, 5)

				this.showSuggestions = this.suggestions.length > 0
			},

			// 关键字高亮处理
			highlightKeyword(text, keyword) {
				if (!text || !keyword) return text

				const regex = new RegExp(keyword, 'gi')
				return text.replace(regex, match => {
					return `<span style="color: #1E90FF; font-weight: bold;">${match}</span>`
				})
			},

			// 执行搜索
			async handleSearch() {
				if (!this.searchKeyword.trim()) {
					uni.showToast({
						title: '请输入搜索内容',
						icon: 'none'
					})
					return
				}

				try {
					this.isSearching = true
					this.networkError = false

					// 检查网络连接
					const isConnected = await this.checkNetworkConnection()
					if (!isConnected) {
						throw new Error('网络连接不可用')
					}

					// 模拟网络请求
					await new Promise(resolve => setTimeout(resolve, 800))

					this.saveSearchHistory(this.searchKeyword)
					this.lastSearchKeyword = this.searchKeyword
					this.showSuggestions = false

					this.searchResults = this.getSearchResults()

					if (this.searchResults.length === 0) {
						this.showEmpty = true
						this.showResults = false
					} else {
						this.showResults = true
						this.showEmpty = false
					}
				} catch (error) {
					console.error('搜索失败:', error)
					this.networkError = true
					this.showResults = false
					this.showEmpty = false
				} finally {
					this.isSearching = false
				}
			},

			// 获取搜索结果
			getSearchResults() {
				if (this.searchKeyword.includes('无结果')) {
					return []
				}

				return mockUsers.filter(item =>
					item.title.includes(this.searchKeyword) ||
					item.tags.some(tag => tag.includes(this.searchKeyword))
				).map(item => ({
					...item,
					title: this.highlightKeyword(item.title, this.searchKeyword)
				}))
			},

			// 重新搜索
			retrySearch() {
				this.networkError = false
				this.handleSearch()
			},

			// 选择建议项
			selectSuggestion(item) {
				this.searchKeyword = item
				this.showSuggestions = false
				this.handleSearch()
			},

			// 删除单条历史记录
			handleDeleteHistory(index, event = {}) {
				// 阻止事件冒泡
				event.stopPropagation && event.stopPropagation()

				// 删除逻辑
				this.searchHistory.splice(index, 1)
				uni.setStorageSync('searchHistory', this.searchHistory)

				// 轻提示
				uni.showToast({
					title: '已删除',
					icon: 'none'
				})
			},

			// 保存搜索历史
			saveSearchHistory(keyword) {
				const index = this.searchHistory.indexOf(keyword)
				if (index !== -1) {
					this.searchHistory.splice(index, 1)
				}
				this.searchHistory.unshift(keyword)
				if (this.searchHistory.length > 10) {
					this.searchHistory.pop()
				}
				uni.setStorageSync('searchHistory', this.searchHistory)
			},

			// 选择历史记录
			selectHistory(item) {
				this.searchKeyword = item
				this.handleSearch()
			},

			// 清空所有历史
			clearAllHistory() {
				this.searchHistory = []
				uni.removeStorageSync('searchHistory')
			},

			// 清除搜索输入
			clearSearchInput() {
				this.searchKeyword = ''
				this.resetToInitialState()
			},

			// 重置搜索状态
			resetSearch() {
				this.searchKeyword = ''
				this.resetToInitialState()
			},

			// 返回初始状态
			resetToInitialState() {
				this.showResults = false
				this.showEmpty = false
				this.showSuggestions = false
				this.networkError = false
			}
		}
	}
</script>

<style lang="scss">
	.search-container {
		padding: 20rpx;
		min-height: 100vh;
		background: #f8f8f8 url('/static/Mask group.png') no-repeat center center;
		background-size: cover;
		position: relative;
	}

	/* 搜索栏样式 */
	.search-bar {
		display: flex;
		align-items: center;
		width: 100%;
		margin: 100rpx 50rpx 0 0;
	}

	.search-input-wrapper {
		flex: 1;
		height: 70rpx;
		background: #FFFFFF;
		border-radius: 35rpx;
		padding: 0 25rpx;
		display: flex;
		align-items: center;
		position: relative;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
	}

	.search-input {
		flex: 1;
		height: 100%;
		font-size: 28rpx;
	}

	.clear-btn {
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.search-button {
		width: 120rpx;
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		background: #1E90FF;
		color: #FFFFFF;
		border-radius: 35rpx;
		font-size: 28rpx;
		margin-left: 20rpx;
		box-shadow: 0 2rpx 6rpx rgba(30, 144, 255, 0.3);
	}

	/* 加载状态 */
	.loading-state {
		padding: 40rpx 0;
		text-align: center;
	}

	/* 搜索建议 */
	.suggestion-list {
		background: #FFFFFF;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.suggestion-item {
		padding: 20rpx;
		font-size: 28rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.suggestion-item:last-child {
		border-bottom: none;
	}

	.history-section {
		background: #FFFFFF;
		border-radius: 16rpx;
		padding: 25rpx;
		margin-top: 20rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
		font-size: 30rpx;
		color: #333;
	}

	.clear-all {
		color: #1E90FF;
		font-size: 26rpx;
	}

	.history-list {
		display: flex;
		flex-wrap: wrap;
	}

	.history-item {
		background: #f5f5f5;
		border-radius: 30rpx;
		padding: 12rpx 25rpx;
		margin-right: 20rpx;
		margin-bottom: 15rpx;
		font-size: 26rpx;
		display: flex;
		align-items: center;
	}

	.delete-btn {
		margin-left: 10rpx;
		padding: 5rpx;
		display: flex;
		align-items: center;
	}

	.result-state {
		background: #FFFFFF;
		border-radius: 16rpx;
		padding: 25rpx;
		margin-top: 20rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}

	.result-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 25rpx;
		font-size: 28rpx;
		color: #333;
	}

	.reset-search {
		color: #1E90FF;
		font-size: 26rpx;
	}

	.result-list {
		max-height: 70vh;
		overflow-y: auto;
	}

	.result-item {
		padding: 25rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.result-item .subtitle {
		font-size: 24rpx;
		color: #999;
		background: #f5f5f5;
		padding: 4rpx 12rpx;
		border-radius: 8rpx;
	}

	.empty-state {
		text-align: center;
		padding: 80rpx 40rpx;
		background: #FFFFFF;
		border-radius: 16rpx;
		margin-top: 20rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}

	.empty-icon {
		width: 180rpx;
		height: 180rpx;
		margin-bottom: 30rpx;
	}

	.empty-text {
		display: block;
		font-size: 30rpx;
		color: #333;
		margin-bottom: 15rpx;
	}

	.empty-tip {
		font-size: 26rpx;
		color: #999;
		display: block;
		margin-bottom: 30rpx;
	}

	.network-error {
		text-align: center;
		padding: 80rpx 40rpx;
		background: #FFFFFF;
		border-radius: 16rpx;
		margin-top: 20rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}

	.error-icon {
		width: 180rpx;
		height: 180rpx;
		margin-bottom: 30rpx;
	}

	.error-text {
		display: block;
		font-size: 30rpx;
		color: #333;
		margin-bottom: 15rpx;
	}

	.retry-btn {
		display: inline-block;
		padding: 12rpx 40rpx;
		background: #1E90FF;
		color: #FFFFFF;
		border-radius: 30rpx;
		font-size: 28rpx;
		margin-top: 20rpx;
	}
</style>